<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title.sync="title" width="940px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="125px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractCode">
            <el-input v-model="form.contractCode" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="form.contractName" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属服务商" prop="serviceproviderId">
            <el-select v-model="form.serviceproviderId" placeholder="所属服务商" :disabled="isView" class="input_text" @change="indexSelect($event)">
              <el-option v-for="(item,index) in serviceproItem" :key="index" :label="item.seproName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contractItemId">
            <el-select v-model="form.contractItemId" placeholder="合同类型" :disabled="isView" class="input_text" @change="indexSelect($event)">
              <el-option v-for="(item,index) in contTypeItem" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="合同内容" prop="contractContent">
            <el-input v-model="form.contractContent" type="textarea" style="width:760px;" :readonly="isView" :rows="4" />
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="form.contractItemId === 21">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同金额（元）" prop="contractMoney">
              <!-- <el-input v-model="contractMoney" :readonly="isView" class="input_text" @keyup.native="oninput(value)" />-->
              <eTable ref="table" :data="contractMoney.tableList" :is-view="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同开始时间" prop="startTime">
                  <el-date-picker
                    v-model="form.startTime"
                    style="width: 300px"
                    type="date"
                    placeholder="请选择"
                    :format="'yyyy-MM-dd'"
                    :picker-options="startTimeConfig"
                    :disabled="isView"
                    @change="startTimeChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同结束时间" prop="endTime">
                  <el-date-picker
                    v-model="form.endTime"
                    style="width: 300px"
                    type="date"
                    placeholder="请选择"
                    :format="'yyyy-MM-dd'"
                    :picker-options="endTimeConfig"
                    :disabled="isView"
                    @change="endTimeChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同签订时间" prop="creatTime">
                  <el-date-picker
                    v-model="form.creatTime"
                    style="width: 300px"
                    type="date"
                    placeholder="请选择"
                    :picker-options="creatTimeConfig"
                    :format="'yyyy-MM-dd'"
                    :disabled="isView"
                    @change="creatTimeChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="附件">
                  <el-upload
                    :before-remove="handleBeforeRemove"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :on-preview="handlePreview"
                    :file-list="files"
                    :headers="headers"
                    :action="imagesUploadApi"
                    class="upload-demo"
                    multiple
                    :disabled="isView"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" style="display: block;width:513px;" class="el-upload__tip">请勿上传违法文件，且文件不超过15M</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                style="width: 300px"
                type="date"
                placeholder="请选择"
                :format="'yyyy-MM-dd'"
                :picker-options="startTimeConfig"
                :disabled="isView"
                @change="startTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                style="width: 300px"
                type="date"
                placeholder="请选择"
                :format="'yyyy-MM-dd'"
                :picker-options="endTimeConfig"
                :disabled="isView"
                @change="endTimeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同签订时间" prop="creatTime">
              <el-date-picker
                v-model="form.creatTime"
                style="width: 300px"
                type="date"
                placeholder="请选择"
                :picker-options="creatTimeConfig"
                :format="'yyyy-MM-dd'"
                :disabled="isView"
                @change="creatTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="form.contractItemId === 22 || form.contractItemId === 171 ? '月服务费（元）':'采购金额（元）'" prop="serveMoney">
              <el-input
                v-model="form.serveMoney"
                :readonly="isView"
                class="input_text"
                @keydown.native="moneyKeyDown"
                @input="moneyChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属系统" prop="eqptsystem">
              <el-select
                v-model="form.eqptsystem"
                class="input_text"
                placeholder="请先选择所属系统"
                :disabled="isView"
                @change="selectFun"
              >
                <el-option
                  v-for="(item, index) in eqptSystemList"
                  :key="item.label + index"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select
                v-model="form.deviceType"
                allow-create
                filterable
                class="input_text"
                placeholder="请先选择设备类型"
                :disabled="isView"
              >
                <el-option
                  v-for="(item, index) in eqptTypeList"
                  :key="item.name + index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备厂家" prop="deviceFactory">
              <el-select
                v-model="form.deviceFactory"
                allow-create
                filterable
                default-first-option
                class="input_text"
                :disabled="isView"
                placeholder="请先选择设备厂家"
                @keyup.enter.native="onSubmitBrand"
                @change="selectBrand"
              >
                <el-option
                  v-for="(item, index) in eqptbrandlist"
                  :key="item.label + index"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceModel">
              <el-select
                v-model="form.deviceModel"
                allow-create
                filterable
                default-first-option
                :disabled="isView"
                class="input_text"
                placeholder="请先选择设备型号"
                @keyup.enter.native="onSubmitModelname"
              >
                <el-option
                  v-for="(item, index) in eqptmodelnamelist"
                  :key="item.id + index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配件描述" prop="partsDescription">
              <el-input v-model="form.partsDescription" :readonly="isView" class="input_text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="area_item" label="地区" prop="serveProvinces" :rules="{ required: true, message: '请选择地区' }">
              <AreaSelect ref="areaSelect" :default-props="form" :disabled="isView" @change="handleSelectArea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务详细地址" prop="serveAddress">
              <el-input v-model="form.serveAddress" :readonly="isView" class="input_text" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.contractItemId === 171 || form.contractItemId === 172" :span="12">
            <el-form-item label="设备成色" prop="deviceCondition">
              <el-select
                v-model="form.deviceCondition"
                class="input_text"
                placeholder="请选择"
                :disabled="isView"
              >
                <el-option
                  v-for="item in condition"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col v-if="form.contractItemId === 172" :span="12">
            <el-form-item label="要求送达日期" prop="serveTime">
              <el-date-picker
                v-model="form.serveTime"
                style="width: 300px"
                type="date"
                placeholder="请选择"
                :format="'yyyy-MM-dd'"
                :picker-options="serveTimeConfig"
                :disabled="isView"
                @change="serveTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件">
              <el-upload
                :before-remove="handleBeforeRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :on-preview="handlePreview"
                :file-list="files"
                :headers="headers"
                :action="imagesUploadApi"
                class="upload-demo"
                multiple
                :disabled="isView"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" style="display: block;width:513px;" class="el-upload__tip">请勿上传违法文件，且文件不超过15M</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="isView===false || isAdd===true" type="text" @click="cancel">取消</el-button>
      <el-button v-show="isAdd===false && isView===true" :loading="loading" type="primary" @click="cancel">返回</el-button>
      <el-button v-show="isView===false" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>
<script>
import request from '@/utils/request'
import { add, edit } from '@/api/tServiceproviderContract'
import { add as addCost, edit as editCost } from '@/api/tEngineerMoney'
import { mapGetters } from 'vuex'
import { del } from '@/api/picture'
import { getToken } from '@/utils/auth'
import { submitBrand, submitModelname, getEqptModel, processEqpt, getEqptType } from '@/utils/util';
import { getDictDetails } from '@/api/dictDetail'
import eTable from './table'
import { validateNumber } from '@/utils/validate'
import AreaSelect from '@/components/AreaSelect'
// import { stringify } from 'qs'

export default {
  components: { eTable, AreaSelect },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      title: '',
      loading: false, dialog: false,
      form: defaultForm,
      contractMoney: {
        tableList: options
      },
      contTypeItem: [],
      serviceproItem: [],
      eqptbrandlist: [],
      eqptmodelnamelist: [],
      eqptTypeList: [],
      eqptSystemList: [],
      region: [],
      files: [],
      confition: [],
      condition: [
        { value: '全新', label: '全新' },
        { value: '九成', label: '九成' },
        { value: '八成', label: '八成' },
        { value: '七成', label: '七成' }
      ],
      rules: {
        eqptsystem: [
          { required: true, message: '请选择所属系统', trigger: 'blur' }
        ],
        contractCode: [
          { required: true, message: '请输入合同编号', trigger: 'blur' }
        ],
        contractName: [
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ],
        contractContent: [
          { required: true, message: '请输入合同内容', trigger: 'blur' }
        ],
        contractItemId: [
          { required: true, message: '请选择合同类型', trigger: 'blur' }
        ],
        serviceproviderId: [
          { required: true, message: '请选择所属服务商', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请输入合同开始时间', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请输入合同结束时间', trigger: 'blur' }
        ],
        creatTime: [
          { required: true, message: '请输入合同签订时间', trigger: 'blur' }
        ],
        serveMoney: [
          { required: true, message: '请输入合同金额', trigger: 'blur' }
        ],
        deviceFactory: [
          { required: true, message: '请输入设备厂家', trigger: 'blur' }
        ],
        deviceType: [
          { required: true, message: '请输入设备类型', trigger: 'blur' }
        ],
        deviceModel: [
          { required: true, message: '请输入设备型号', trigger: 'blur' }
        ],
        serveAddress: [
          { required: true, message: '请输入服务详细地址', trigger: 'blur' }
        ],
        serveTime: [
          { required: true, message: '请输入要求送达日期', trigger: 'blur' }
        ],
        deviceCondition: [
          { required: true, message: '请输入设备成色', trigger: 'blur' }
        ]
      },
      startTimeConfig: {
        disabledDate: (time) => {
          const self = this
          if (self.form.endTime) {
            return time.getTime() > new Date(self.form.endTime).getTime()
          }
        }
      },
      // 结束时间配置
      endTimeConfig: {
        disabledDate: (time) => {
          const self = this
          if (self.form.startTime) {
            return time.getTime() < new Date(self.form.startTime).getTime()
          }
        }
      },
      creatTimeConfig: {
        disabledDate: (time) => {
          const self = this
          if (self.form.creatTime) {
            return time.getTime() < new Date(self.form.creatTime).getTime()
          }
        }
      },
      serveTimeConfig: {
        disabledDate: (time) => {
          const self = this
          if (self.form.serveTime) {
            return time.getTime() < new Date(self.form.serveTime).getTime()
          }
        }
      }
    } // end of return
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  mounted: function() {
    this.byNameinfo('合同类型')
    this.tServiceproviderInfoAll()
    this.getEqptBrand()
    this.getEqptSystem()
    this.title = this.isAdd ? '新增' : (this.isView === true ? '详情' : '编辑')
  },
  methods: {
    startTimeChange(val) {
      this.form.startTime = val
    },
    endTimeChange(val) {
      this.form.endTime = val
    },
    creatTimeChange(val) {
      console.log(val)
      this.form.creatTime = val
    },
    serveTimeChange(val) {
      this.form.serveTime = val
    },
    // --------------------------
    tServiceproviderInfoAll() {
      this.getAllService().then(res => {
        this.serviceproItem = res
      })
    },
    getAllService() {
      return request({
        url: 'api/tServiceproviderInfoAll',
        method: 'get'
      })
    },
    moneyKeyDown(event) {
      validateNumber(event)
    },
    moneyChange(value) {
      var str = this.form.contractMoney
      // 限制只能输入一个小数点
      if (str.indexOf('.') !== -1) {
        var str_ = str.substr(str.indexOf('.') + 1)
        if (str_.length > 2) {
          str = str.substr(0, str.indexOf('.') + 1) + str_.substr(0, 2)
        }
      }
      // str = str.replace(/\.\d\d\d$/,'') // 小数点后只能输两位
      this.form.contractMoney = str
    },
    byNameinfo(name) {
      this.byName(name).then(res => {
        this.bydictId(res.id).then(resobject => {
          this.contTypeItem = resobject
        })
      })
    },
    // 获取id值
    byName(name) {
      return request({
        url: 'api/dict/byName/' + name,
        method: 'get'
      })
    },
    // 获取id值
    bydictId(id) {
      return request({
        url: 'api/dictDetail/findByDeptId/' + id,
        method: 'get'
      })
    },
    cancel() {
      this.resetForm()
    },
    indexSelect(event) {

    },
    doSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          const fileIds = []
          this.files.forEach(function(data, index) {
            fileIds.push(data.id)
          })
          this.form.attachments = fileIds.join(',')
          if (this.isAdd) {
            this.doAdd()
          } else this.doEdit()
        } else {
          return false
        }
      })
    },
    doAdd() {
      const { eqptsystem, ...form } = this.form;
      console.log(eqptsystem)
      form.engineerMoney = JSON.stringify(this.contractMoney.tableList)
      add(form).then(res => {
        // this.doAddCost(this.contractMoney, form, res); 合并在一起
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    // 该函数不用
    doAddCost(contractMoney, form, res) {
      const list = contractMoney.tableList.map((item) => {
        return {
          ...item,
          contractId: res.id,
          contractCode: form.contractCode
        }
      })
      addCost(list).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      const { eqptsystem, ...form } = this.form;
      console.log(eqptsystem)
      form.engineerMoney = JSON.stringify(this.contractMoney.tableList)
      edit(form).then(res => {
        // this.doEditCost(this.contractMoney, form)
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        console.log('enter....')
        this.supThis.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    // 以下接口不用
    doEditCost(contractMoney, form) {
      const list = contractMoney.tableList.map((item) => {
        return {
          ...item,
          contractCode: form.contractCode
        }
      })
      editCost(list).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        console.log('enter....')
        this.supThis.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      // this.$refs['areaSelect'].clear() todo@@@@@
      this.files = []
      this.form = defaultForm
      this.contractMoney = {
        tableList: options
      }
    },
    handlePreview(file) {
      window.open(file.url, '_blank')
    },
    handleSuccess(response, file, fileList) {
      const id = response.data[0]
      this.files.push({ name: id, url: '/api/picture/' + id, id: id })
    },
    handleBeforeRemove(file, fileList) {
      const _this = this
      for (let i = 0; i < this.files.length; i++) {
        if (this.files[i].id === file.name) {
          del(this.files[i].id).then(res => {
            _this.files.splice(i, 1)
          })
          return true
        }
      }
    },
    handlePictureCardPreview(file) {
      window.open(file.url, '_blank')
    },
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    },
    selectFun(val) {
      const target = this;
      this.eqptsystem = val;
      getEqptType(this.eqptsystem, target, 'eqptTypeList', 'deviceType')
    },
    onSubmitBrand() {
      const target = this;
      submitBrand(target, 'deviceFactory')
    },
    selectBrand(val) {
      const target = this;
      if (val) {
        getEqptModel(val, target, 'eqptmodelnamelist').then((res) => {
          processEqpt(res, target, 'eqptmodelnamelist', 'deviceModel')
        })
      }
    },
    onSubmitModelname() {
      const target = this;
      submitModelname(target, 'deviceFactory', 'deviceModel')
    },
    getEqptBrand() {
      getDictDetails('eqpt_brand').then(res => {
        this.eqptbrandlist = res.content
      })
    },
    getEqptSystem() {
      getDictDetails('eqpt_system').then(res => {
        this.eqptSystemList = res.content
      })
    },
    handleSelectArea(countryItem, provinceItem, cityItem, areaItem) {
      this.form.serveCountry = countryItem.name
      this.form.serveProvinces = provinceItem.name
      this.form.serveCity = cityItem.name
      this.form.serveCounty = areaItem.name
    }
  }
}

const options = [
  {
    engineerType: '网络',
    engineerLevel: '初级',
    engineerCost: ''
  },
  {
    engineerType: '网络',
    engineerLevel: '中级',
    engineerCost: ''
  },
  {
    engineerType: '网络',
    engineerLevel: '高级',
    engineerCost: ''
  },
  {
    engineerType: '系统',
    engineerLevel: '初级',
    engineerCost: ''
  },
  {
    engineerType: '系统',
    engineerLevel: '中级',
    engineerCost: ''
  },
  {
    engineerType: '系统',
    engineerLevel: '高级',
    engineerCost: ''
  },
  {
    engineerType: '弱电',
    engineerLevel: '初级',
    engineerCost: ''
  },
  {
    engineerType: '弱电',
    engineerLevel: '中级',
    engineerCost: ''
  },
  {
    engineerType: '弱电',
    engineerLevel: '高级',
    engineerCost: ''
  }
]

const defaultForm = {
  id: '',
  contractCode: '',
  attachments: '',
  contractName: '',
  contractContent: '',
  contractItemId: 21,
  contractItemName: '',
  customerId: '',
  customerName: '',
  startTime: '',
  endTime: '',
  creatTime: '',
  serveMoney: '',
  eqptsystem: '',
  deviceFactory: '',
  deviceType: '',
  deviceModel: '',
  partsDescription: '',
  serveCountry: '',
  serveProvinces: '',
  serveCity: '',
  serveCounty: '',
  serveAddress: '',
  serveTime: '',
  deviceCondition: ''
};
</script>

<style lang="scss" scoped>
.input_text {
  width: 300px;
}

.area_item {
  .el-cascader {
    display: block;
  }
}
</style>
